package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.ruoyi.common.core.domain.PushMessageVO;
import com.ruoyi.common.core.enums.PushType;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.domain.SysMsgSend;
import com.ruoyi.system.domain.SysMsgTemplate;
import com.ruoyi.system.domain.SysUserLabel;
import com.ruoyi.system.mapper.SysMsgSendMapper;
import com.ruoyi.system.mapper.SysUserLabelMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.IMsgPushService;
import com.ruoyi.system.service.ISysMsgSendService;
import com.ruoyi.system.service.ISysMsgTemplateService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息发布Service业务层处理
 *
 * @author zmc
 * @date 2022-05-25
 */
@Service
@Slf4j
public class SysMsgSendServiceImpl implements ISysMsgSendService {
    @Autowired
    private SysMsgSendMapper sysMsgSendMapper;

    @Autowired
    private ISysMsgTemplateService sysMsgTemplateService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IMsgPushService msgPushService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserLabelMapper sysUserLabelMapper;

    /**
     * 查询消息发布
     *
     * @param id 消息发布ID
     * @return 消息发布
     */
    @Override
    public SysMsgSend selectSysMsgSendById(String id) {
        SysMsgSend sysMsgSend = sysMsgSendMapper.selectSysMsgSendById(id);
        List<String> list = new ArrayList<>();
        if(sysMsgSend.getMsgNotice().equals(1)){
            list.add("通知栏");
        }
        if(sysMsgSend.getMsgSys().equals(1)){
            list.add("系统消息");
        }
        if(sysMsgSend.getMsgWx().equals(1)){
            list.add("微信消息");
        }
        sysMsgSend.setTemplateType(list);
        return sysMsgSend;
    }

    /**
     * 查询消息发布列表
     *
     * @param sysMsgSend 消息发布
     * @return 消息发布
     */
    @Override
    public List<SysMsgSend> selectSysMsgSendList(SysMsgSend sysMsgSend) {
        return sysMsgSendMapper.selectSysMsgSendList(sysMsgSend);
    }

    /**
     * 新增消息发布
     *
     * @param sysMsgSend 消息发布
     * @return 结果
     */
    @Override
    public int insertSysMsgSend(SysMsgSend sysMsgSend) {
        int result = 0;
        sysMsgSend.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
        sysMsgSend.setCreateTime(DateUtils.getNowDate());
        sysMsgSend.setCreateBy(SecurityUtils.getUsername());
        if(StringUtils.isNotEmpty(sysMsgSend.getTemplateType())){
            for(String type:sysMsgSend.getTemplateType()){
                if(type.equals("系统消息")){
                    sysMsgSend.setMsgSys(1);
                }else if(type.equals("微信消息")){
                    sysMsgSend.setMsgWx(1);
                }else if(type.equals("通知栏")){
                    sysMsgSend.setMsgNotice(1);
                }
            }

        }
        result = sysMsgSendMapper.insertSysMsgSend(sysMsgSend);
        sendSystemMsg(sysMsgSend);
        sendNoticeMsg(sysMsgSend);
        return result;
    }

    private int sendSystemMsg(SysMsgSend sysMsgSend){
        int result =0;
        if(sysMsgSend.getMsgSys() !=null && sysMsgSend.getMsgSys() == 1 && sysMsgSend.getSendStatus().equals("0") && StringUtils.isNull(sysMsgSend.getUserId())){
            //查询用户
            List<SysUser> sysUserList = sysUserMapper.selectUserList(new SysUser());
            //生成消息，批量插入
            List<SysMsgSend> sysMsgSends = new ArrayList<>(sysUserList.size());
            for(SysUser sysUser:sysUserList){
                SysMsgSend newObject = new SysMsgSend();
                BeanUtil.copyProperties(sysMsgSend,newObject);
                newObject.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
                newObject.setUserId(sysUser.getUserId());
                newObject.setSendStatus("1");
                sysMsgSends.add(newObject);
            }
            result = sysMsgSendMapper.batchSysMsg(sysMsgSends);
            //更新 sendStatus
            sysMsgSend.setSendStatus("1");
            sysMsgSendMapper.updateSysMsgSend(sysMsgSend);
        }
        return result;
    }

    private int sendNoticeMsg(SysMsgSend sysMsgSend){
        int result =0;
        if(sysMsgSend.getMsgNotice() != null && sysMsgSend.getMsgNotice() == 1 && sysMsgSend.getSendStatus().equals("0") && StringUtils.isNull(sysMsgSend.getUserId())){
            if(StringUtils.isNotEmpty(sysMsgSend.getModuleType())){
                //查询标签 用户 userid
                SysUserLabel label = new SysUserLabel();
                label.setModuleLabel(sysMsgSend.getModuleType());
                List<SysUserLabel> sysUserLabels = sysUserLabelMapper.selectSysUserLabelList(label);
                //批量插入 sendMsg,sendStatus 0
                List<SysMsgSend> sysMsgSends = new ArrayList<>(sysUserLabels.size());
                for(SysUserLabel userLabel:sysUserLabels){
                    SysMsgSend newObject = new SysMsgSend();
                    BeanUtil.copyProperties(sysMsgSend,newObject);
                    newObject.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
                    newObject.setUserId(userLabel.getUserId());
                    newObject.setSendStatus("0");
                    sysMsgSends.add(newObject);
                }
                result = sysMsgSendMapper.batchSysMsg(sysMsgSends);
            }
            sysMsgSend.setSendStatus("1");
            sysMsgSendMapper.updateSysMsgSend(sysMsgSend);
        }
        return result;
    }

    //定时任务，查询 通知栏 0 UserId 不为null 单推
     public int getuiSendNoticeMsg(){
        int result =0;
         SysMsgSend sysMsgSend = new SysMsgSend();
         sysMsgSend.setMsgNotice(0);
         sysMsgSend.setSendStatus("0");
        List<SysMsgSend> sysMsgSends = sysMsgSendMapper.selectSysMsgSendList(sysMsgSend);
        for(SysMsgSend send:sysMsgSends){
            //getui
            if(StringUtils.isNotNull(send.getUserId())){
                int tmp = sendSingleSms(send);
                if(tmp == 1 ){
                    send.setSendStatus("1");
                }
            }
        }
        //批量更新发送状态
         if(StringUtils.isNotEmpty(sysMsgSends)){
             result = sysMsgSendMapper.batchUpdateSendStatus(sysMsgSends);
         }
        return result;
     }

     private void batchUpdateSendStatus(List<SysMsgSend> sysMsgSends,String state){
        sysMsgSends.stream().forEach(item->{
            item.setSendStatus(state);
        });
        sysMsgSendMapper.batchUpdateSendStatus(sysMsgSends);
     }

    private int sendSingleSms(SysMsgSend sysMsgSend){
        int result =0;
        //异步Queue,或者调用接口，发送消息。
        PushMessageVO pushMsgVO = new PushMessageVO();
        PushMessageVO.NotificationDTO notificationDTO = new PushMessageVO.NotificationDTO();
        notificationDTO.setTitle(sysMsgSend.getTitle());
        notificationDTO.setBody(sysMsgSend.getContent());
        notificationDTO.setClick_type("startapp");
        //notificationDTO.setUrl("http://www.baidu.com");
        pushMsgVO.setNotification(notificationDTO);
        //获取cid
        List<String> users = new ArrayList<>();
        if(sysMsgSend.getUserId().toString() !=null && StringUtils.isNotBlank(sysMsgSend.getUserId().toString())){
            users.add(sysMsgSend.getUserId().toString());
            result = msgPushService.pushToAPP(PushType.SINGLE.getCode(),pushMsgVO,users);
        }else {
            log.error("sys_msg_send, " + "id:" + sysMsgSend.getId() +" ," + "userId " + "无效");
        }
        return result;
    }

    /**
     * 修改消息发布
     *
     * @param sysMsgSend 消息发布
     * @return 结果
     */
    @Override
    public int updateSysMsgSend(SysMsgSend sysMsgSend) {
        sysMsgSend.setUpdateTime(DateUtils.getNowDate());
        sysMsgSend.setUpdateBy(SecurityUtils.getUsername());
        sysMsgSend.setMsgSys(0);
        sysMsgSend.setMsgWx(0);
        sysMsgSend.setMsgNotice(0);
        if(StringUtils.isNotEmpty(sysMsgSend.getTemplateType())){
            for(String type:sysMsgSend.getTemplateType()){
                if(type.equals("系统消息")){
                    sysMsgSend.setMsgSys(1);
                }else if(type.equals("微信消息")){
                    sysMsgSend.setMsgWx(1);
                }else if(type.equals("通知栏")){
                    sysMsgSend.setMsgNotice(1);
                    sendNoticeMsg(sysMsgSend);
                }
            }

        }
        return sysMsgSendMapper.updateSysMsgSend(sysMsgSend);
    }

    /**
     * 批量删除消息发布
     *
     * @param ids 需要删除的消息发布ID
     * @return 结果
     */
    @Override
    public int deleteSysMsgSendByIds(String[] ids) {
        return sysMsgSendMapper.deleteSysMsgSendByIds(ids);
    }

    /**
     * 删除消息发布信息
     *
     * @param id 消息发布ID
     * @return 结果
     */
    @Override
    public int deleteSysMsgSendById(String id) {
        return sysMsgSendMapper.deleteSysMsgSendById(id);
    }

    @Override
    public int sendSingleSmsToAdmin(String mobile, Long userId, String templateId, Map<String, Object> templateParams) {
        log.info("send sms:" + mobile +","+ userId +","+ templateId + ","+ templateParams.values().toString());
        // 如果 mobile 为空，则加载用户编号对应的手机号
        if (StrUtil.isEmpty(mobile)) {
            SysUser user = sysUserService.selectUserById(userId);
            if (user != null) {
                mobile = user.getPhonenumber();
            }
        }
        sendSingleSms(mobile,userId,1,templateId,templateParams);
        return 1;
    }

    @Override
    public int sendSingleSms(String mobile, Long userId, Integer userType,
                              String templateId, Map<String, Object> templateParams){
        int result = 0;
        //获取模板内容
        SysMsgTemplate msgTemplate = sysMsgTemplateService.selectSysMsgTemplateById(templateId);
        //替换参数
        SysMsgSend sysMsgSend = createSysMsgSendByTemplate(msgTemplate,templateParams);
        sysMsgSend.setUserId(userId);
        //插入log数据库
        result = this.insertSysMsgSend(sysMsgSend);
        //异步Queue,或者调用接口，发送消息。
        PushMessageVO pushMsgVO = new PushMessageVO();
        PushMessageVO.NotificationDTO notificationDTO = new PushMessageVO.NotificationDTO();
        notificationDTO.setTitle("test");
        notificationDTO.setBody("test");
        notificationDTO.setClick_type("url");
        notificationDTO.setUrl("http://www.baidu.com");
        pushMsgVO.setNotification(notificationDTO);
        //获取cid
        List<String> users = new ArrayList<>();
        users.add("12");
        msgPushService.pushToAPP(PushType.SINGLE.getCode(),pushMsgVO,users);
        return result;

    }

    @Override
    public int insertSysMsgSendByTemplate(SysMsgTemplate sysMsgTemplate, List<String> paramsValues) {
        //生成消息
        SysMsgSend sysMsg = createSysMsgSendByTemplate(sysMsgTemplate,paramsValues);

        return this.insertSysMsgSend(sysMsg);
    }

    private SysMsgSend createSysMsgSendByTemplate(SysMsgTemplate sysMsgTemplate,List<String> paramsValues){
        Map<String,Object> templateParams = new HashMap<>();
        //构造map参数
        //string params
        if(paramsValues.size()>0){
            int i=0;
            List<String> keys = sysMsgTemplate.getParamList();
            for(String value :paramsValues){
                templateParams.put(keys.get(i),value);
                i++;
            }
        }
        return createSysMsgSendByTemplate(sysMsgTemplate,templateParams);
    }
    private SysMsgSend createSysMsgSendByTemplate(SysMsgTemplate sysMsgTemplate,Map<String,Object> templateParams){
        SysMsgSend sysMsg = new SysMsgSend();
        //sysMsg.setTemplateType(sysMsgTemplate.getTempType());
        sysMsg.setMsgNotice(sysMsgTemplate.getMsgNotice());
        sysMsg.setMsgSys(sysMsgTemplate.getMsgSys());
        sysMsg.setMsgWx(sysMsgTemplate.getMsgWx());
        sysMsg.setTemplateId(sysMsgTemplate.getId());
        sysMsg.setModuleType(sysMsgTemplate.getModuleType());
        sysMsg.setTitle(sysMsgTemplate.getTitle());
        sysMsg.setContent(formatSmsTemplateContent(sysMsgTemplate.getContent(),templateParams));
        return sysMsg;
    }
    private int processMsg(String userId,String templateId,Map<String, Object> templateParams){
        int resulst = 0;
        // 处理逻辑
        //个推
        //系统消息
        //
        return resulst;
    }

    private String formatSmsTemplateContent(String content, Map<String, Object> params) {
        //return StrUtil.format(content, params);
        //freemarker 模板解析
        TemplateEngine engine = TemplateUtil.createEngine();
        Template template = engine.getTemplate(content);
        String result = template.render(params);
        return result;
    }

}
